//
//  MinesViewController.m
//  MyNewProject
//
//  Created by 王春辉 on 2019/12/29.
//  Copyright © 2019年 sun. All rights reserved.
//

#import "MinesViewController.h"
#import "MineTableViewCell.h"
#import "AddressListVC.h"
#import "MyOrderViewController.h"
#import "WalletViewController.h"
#import "CouponViewController.h"
#import "HelpingCenterVC.h"
#import "CertifyViewController.h"
#import "SetUpViewController.h"
#import "AuctionMessageVC.h"
#import "MyPromoCodeVC.h"
#import "AuctionOrderListVC.h"

#pragma mark -- mark 数据相关
#import "UserInfoModel.h"

static NSString *identifier = @"cell_identifier";
@interface MinesViewController () <UITableViewDelegate, UITableViewDataSource> {
    UIImageView *_headerImageView; // 头像
    UILabel *_accountLabel; // 账户信息
    UILabel *_idNumLabel; // 用户id
    UILabel *_levelLabel; // 等级label
    UIButton *_loginBtn; // 登录按钮
    
    BOOL _isLogin; // 是否登陆
}

/**
 tableView
 */
@property (nonatomic, strong) UITableView *tableView;

/**
 headView
 */
@property (nonatomic, strong) UIView *headView;

/**
 cell的标签
 */
@property (nonatomic, strong) NSArray <NSString *>*titleNames;

@end

@implementation MinesViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestUserInfo];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"我的";
    [self initContentViews];
}

- (void)initContentViews {
    CGFloat headerViewHeight = 329.0 / 667 * self.view.height;
    self.headView.frame = CGRectMake(0, 0, self.view.width, headerViewHeight);
    self.tableView.tableHeaderView = self.headView;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(SKTopBar_Height);
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(-SKBottomSafe_Height);
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestUserInfo)];
}

#pragma mark -- mark 懒加载

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.showsVerticalScrollIndicator = false;
        _tableView.showsHorizontalScrollIndicator = false;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = SKColorWithHex(0xF7F7F7);
        [_tableView registerClass:[MineTableViewCell class] forCellReuseIdentifier:identifier];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)headView {
    if (!_headView) {
        _headView = [[UIView alloc] init];
        // height : 318.5
        _headView.backgroundColor = SKColorWithHex(0xF7F7F7);
        
        UIView *view1 = [[UIView alloc] init];
        view1.backgroundColor = [UIColor whiteColor];
        // 100.0
        
        [_headView addSubview:view1];
        
        UIView *view2 = [[UIView alloc] init];
        view2.backgroundColor = [UIColor whiteColor];
        // 114.0
        
        [_headView addSubview:view2];
        
        UIView *view3 = [[UIView alloc] init];
        view3.backgroundColor = [UIColor whiteColor];
        // 85.0
        
        [_headView addSubview:view3];
        
        CGFloat height1 = 100.0 / 667 * self.view.height;
        CGFloat height2 = 114.0 / 667 * self.view.height;
        CGFloat height3 = 85.0 / 667 * self.view.height;
        
        CGFloat margin = ((329.0 - 100.0 - 114.0 - 85.0) / 667.0 * self.view.height ) / 3;
        
        view1.frame = CGRectMake(0, 0, self.view.width, height1);
        view2.frame = CGRectMake(0, view1.bottom + margin, self.view.width, height2);
        view3.frame = CGRectMake(0, view2.bottom + margin, self.view.height, height3);
        
        // view1
        UIImageView *headerImageView = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"mine_header_btn_img")];
        headerImageView.frame = CGRectMake(10, 10, height1 - 20, height1 - 20);
        headerImageView.layer.masksToBounds = true;
        headerImageView.layer.cornerRadius = height1 * 0.5 - 10;
        [view1 addSubview:headerImageView];
        
        UILabel *accountNumberLabel = [[UILabel alloc] init];
        accountNumberLabel.textColor = SKColorWithHex(0x333333);
        accountNumberLabel.font = SKFONT_BOLD_SIZE(13);
        accountNumberLabel.text = @"183****0000";
        accountNumberLabel.frame = CGRectMake(headerImageView.right + 10, headerImageView.top + 10, 92, 13);
        [view1 addSubview:accountNumberLabel];
        
        UILabel *userName = [[UILabel alloc] init];
        userName.textColor = SKColorWithHex(0x333333);
        userName.font = SKFONT_Medium(12);
        userName.text = @"用户ID：9609797";
        userName.frame = CGRectMake(accountNumberLabel.left, headerImageView.bottom - 10 - 12, 100, 12);
        [view1 addSubview:userName];
        
        UIButton *reloginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [reloginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [reloginBtn addTarget:self action:@selector(reloginButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        reloginBtn.titleLabel.font = SKFONT_BOLD_SIZE(21);
        [reloginBtn setTitleColor:SKColorWithHex(0x333333) forState:UIControlStateNormal];
        reloginBtn.frame = CGRectMake(headerImageView.right + 10, (height1 - 20) * 0.5, 50, 20);
        [view1 addSubview:reloginBtn];
        
        UIButton *messageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [messageBtn setImage:SKIMAGE_NAMED(@"aution_messge_btn_img") forState:UIControlStateNormal];
        [messageBtn addTarget:self action:@selector(messageButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [view1 addSubview:messageBtn];
        messageBtn.frame = CGRectMake(self.view.width - 10 - 24, (height1 - 24)* 0.5, 24, 24);
        
        UILabel *levelLabel = [[UILabel alloc] init];
        levelLabel.text = @"V0 青铜";
        levelLabel.textColor = [UIColor whiteColor];
        levelLabel.font = SKFONT_Medium(12);
        levelLabel.textAlignment = NSTextAlignmentCenter;
        levelLabel.backgroundColor = SKColorWithHex(0xEAC1A3);
        levelLabel.layer.masksToBounds = true;
        levelLabel.layer.cornerRadius = 3.0;
        [view1 addSubview:levelLabel];
        levelLabel.frame = CGRectMake(accountNumberLabel.right + 6, accountNumberLabel.centerY - 10, 52, 20);
        
        // view2
        NSArray *titles = @[
            @"成交记录",
            @"我的地址",
            @"我的钱包",
            @"优惠券"];
        NSArray *imageNames = @[
            @"mine_deal_logs_btn_img",
            @"mine_address_btn_img",
            @"mine_wallet_btn_img",
            @"mine_coupons_btn_img"];
        CGFloat leftMargin = 15.0;
        CGFloat topMargin = 20.0;
        CGFloat bottomMargin = 20.0;
        CGFloat centerMarginV = 10.0;
        CGFloat label_height = 13.0;
        CGFloat btn_l = height2 - topMargin - bottomMargin - label_height - centerMarginV;
        CGFloat centerMarginH = (self.view.width - leftMargin * 2 - btn_l * titles.count) / (titles.count - 1);
        
        for (NSInteger index = 0; index < titles.count; index++) {
            NSString *title = titles[index];
            NSString *imageName = imageNames[index];
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setImage:SKIMAGE_NAMED(imageName) forState:UIControlStateNormal];
            btn.tag = 520 + index;
            [btn addTarget:self action:@selector(headerCenterButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [view2 addSubview:btn];
            btn.frame = CGRectMake(leftMargin + (btn_l + centerMarginH) * index, topMargin, btn_l, btn_l);
            
            UILabel *label = [[UILabel alloc] init];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = title;
            label.textColor = SKColorWithHex(0x333333);
            label.font = SKFONT_SIZE(13);
            [view2 addSubview:label];
            label.frame = CGRectMake(btn.left - 5, btn.bottom + centerMarginV, btn_l + 10, label_height);
        }
        
        // view3
        
        CGFloat leftMargin3 = 23.0;
        CGFloat topMargin3 = 21.0;
        CGFloat bottomMargin3 = 21.0;
        CGFloat centerMarginV3 = 8.5;
        CGFloat label_height3 = 12.0;
        CGFloat btn_l3 = height3 - topMargin3 - bottomMargin3 - centerMarginV3 - label_height3;
        CGFloat centerMarginH3 = (self.view.width - leftMargin3 * 2.0 - btn_l3 * 5.0) / 4.0;
        
        NSArray *imageNames3 = @[@"mine_orders_pending_payment_btn_img",
                                @"mine_orders_to_be_delivered_btn_img",
                                @"mine_orders_to_be_received_btn_img",
                                @"mine_orders_received_btn_img",
                                @"mine_orders_all_btn_img"];
        NSArray *titles3 = @[@"待付款",
                             @"待发货",
                             @"已收货",
                             @"已签收",
                             @"全部订单"];
        
        for (NSInteger index = 0; index < imageNames3.count; index++) {
            NSString *title = titles3[index];
            NSString *imageName = imageNames3[index];
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setImage:SKIMAGE_NAMED(imageName) forState:UIControlStateNormal];
            btn.tag = 520 + index;
            [btn addTarget:self action:@selector(headerBottomButtonsClick:) forControlEvents:UIControlEventTouchUpInside];
            [view3 addSubview:btn];
            btn.frame = CGRectMake(leftMargin3 + index * (btn_l3 + centerMarginH3), topMargin3, btn_l3, btn_l3);
            
            UILabel *label = [[UILabel alloc] init];
            label.text = title;
            label.textAlignment = NSTextAlignmentCenter;
            label.font = SKFONT_SIZE(12);
            label.textColor = SKColorWithHex(0x909090);
            [view3 addSubview:label];
            label.frame = CGRectMake(btn.left - 14, btn.bottom + centerMarginV3, btn_l3 + 28, label_height3);
        }
        _loginBtn = reloginBtn;
        _headerImageView = headerImageView;
        _accountLabel = accountNumberLabel;
        _idNumLabel = userName;
        _levelLabel = levelLabel;
        _loginBtn.hidden = true; // 默认隐藏登录按钮
    }
    return _headView;
}

- (NSArray<NSString *> *)titleNames {
    NSString *s = [[UserInfoSingleton shareInstance].userInfo applyTitle];
    s = (s.length > 0) ? s : @"成为创客";
    NSArray *arr = @[@"实名认证",
                     @"我的二维码",
                     s,
                     @"帮助中心",
                     @"设置"];
    return arr;
}


#pragma mark -- mark UITableViewDelegate UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = SKFONT_SIZE(15);
    if (indexPath.row == 2) {
        cell.textLabel.textColor = SKColorWithHex(0xE33030); }
    cell.textLabel.text = self.titleNames[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    if (![[UserInfoSingleton shareInstance].userInfo isLogin]) {
        [self showMessage:@"请登录"];
        return;
    }
    if (indexPath.row == 0) {
        // 实名认证
        if ([[UserInfoSingleton shareInstance].userInfo isRealCertify]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"你已认证，是否重新上传认证信息" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"重新认证" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                CertifyViewController *vc = [[CertifyViewController alloc] init];
                [self.navigationController pushViewController:vc animated:true];
            }];
            [alert addAction:cancel];
            [alert addAction:sure];
            [self presentViewController:alert animated:true completion:nil];
        }else {
            CertifyViewController *vc = [[CertifyViewController alloc] init];
            [self.navigationController pushViewController:vc animated:true];
        }
    }else if (indexPath.row == 1){
        // 我的二维码
        [self myPopularize];
    } else if (indexPath.row == 2) {
        // 成为创客
        if ([[UserInfoSingleton shareInstance].userInfo canApply]) {
            [self requestBeChuangKe];
        }
    }else if (indexPath.row == 3) {
        // 帮助中心
        HelpingCenterVC *vc = [[HelpingCenterVC alloc] init];
        [self.navigationController pushViewController:vc animated:true];
    }else if (indexPath.row == 4) {
        // 设置
        SetUpViewController *vc = [[SetUpViewController alloc] init];
        [self.navigationController pushViewController:vc animated:true];
    }else {}
}
- (CGFloat)cellHeightForIndexPath:(NSIndexPath *)indexPath cellContentViewWidth:(CGFloat)width tableView:(UITableView *)tableView {
    return self.view.height * (49.0 / 667);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleNames.count;
}


#pragma mark -- mark 获取网络数据
- (void)requestUserInfo {
    if (!(self.uid.length > 0 && self.loginKey.length > 0)) {
        // 未登录
        [self.tableView.mj_header endRefreshing];
        [self refreshUerinfoWith:nil];
        [self.tableView reloadData];
        return;
    }
    NSDictionary *param = @{@"uid":@([self.uid intValue]),
                            @"loginKey":self.loginKey };
    _isLogin = false;
    SKWeakSelf;
    [YQNetworking getWithUrl:@"my/getUserInfo" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        [weakSelf.tableView.mj_header endRefreshing];
        UserInfoModel *model = [UserInfoModel modelWithDictionary:response];
        if ([model isSuccess]) {
            // 登录状态
            [weakSelf refreshUerinfoWith:model.user_info];
            YPLoginUserInfo *info = [YPLoginUserInfo modelObjectWithDictionary: model.user_info.modelToJSONObject];
            [UserInfoSingleton shareInstance].userInfo = info;
            SKUserUserDefaults_Save(response[@"user_info"] , @"UserInfo");
            [weakSelf.tableView reloadData];
        }else {
            // 登陆失效
            [weakSelf showMessage:model.msg];
            [weakSelf refreshUerinfoWith:nil];
        }
        [weakSelf.tableView.mj_header endRefreshing];
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

/**
 成为创客
 */
- (void)requestBeChuangKe {
    NSDictionary *param = @{@"uid":@([self.uid integerValue]),
                            @"loginKey":self.loginKey };
    SKWeakSelf;
    [YQNetworking getWithUrl:@"my/setChuangke" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        WJBaseModel *model = [WJBaseModel modelWithDictionary:response];
        if ([model isSuccess]) {
            [weakSelf showMessage:model.msg];
        }else {
            NSString *s = response[@"url"];
            if ([s isEqualToString:@"goodIndex"]) {
                [weakSelf showMessage:model.msg];
                weakSelf.view.userInteractionEnabled = false;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    weakSelf.view.userInteractionEnabled = true;
                    [(UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController setSelectedIndex:0];
                });
            }else {
                [weakSelf showMessage:model.msg];
            }
            
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}

/**
 我的推广
 */
- (void)myPopularize {
    MyPromoCodeVC * helpingVC = [MyPromoCodeVC new];
    [self.navigationController pushViewController:helpingVC animated:YES];
}

#pragma mark -- mark 业务逻辑
- (void)refreshUerinfoWith:(UserInfoDataModel *)model {
    if (model) {
        _isLogin = true;
        // 获取用户信息成功
        _loginBtn.hidden = true;
        _headerImageView.hidden = false;
        [_headerImageView sd_setImageWithURL:[NSURL URLWithString:model.head_url] placeholderImage:SKIMAGE_NAMED(@"mine_header_btn_img")];
        _accountLabel.text = model.nickname ? model.nickname : @"未设置";
        _accountLabel.hidden = false;
        _idNumLabel.text = [NSString stringWithFormat:@"用户ID：%@", model.uid];
        _idNumLabel.hidden = false;
        _levelLabel.text = model.user_type;
        _levelLabel.hidden = true;
    }else {
        // 获取用户信息失败
        _loginBtn.hidden = false;
        _headerImageView.hidden = false;
        _headerImageView.image = SKIMAGE_NAMED(@"mine_header_btn_img");
        _accountLabel.text = @" ";
        _accountLabel.hidden = true;
        _idNumLabel.text = @" ";
        _idNumLabel.hidden = true;
        _levelLabel.text = @" ";
        _levelLabel.hidden = true;
    }
    
}

#pragma mark -- mark EVENT

/**
 登录按钮点击事件

 @param sender sender
 */
- (void)reloginButtonClick:(UIButton *)sender {
    [AppDelegate pushLoginView];
}

/**
 消息中心

 @param sender sender
 */
- (void)messageButtonClick:(UIButton *)sender {
    if (!(self.uid.length > 0 && self.loginKey.length > 0)) {
        [self showMessage:@"请登录"];
        return;
    }
    AuctionMessageVC *vc = [[AuctionMessageVC alloc] init];
    [self.navigationController pushViewController:vc animated:true];
}

/**
 中间那个view

 @param sender sender
 */
- (void)headerCenterButtonClick:(UIButton *)sender {
    if (!(self.uid.length > 0 && self.loginKey.length > 0)) {
        [self showMessage:@"请登录"];
        return;
    }
    NSInteger tag = sender.tag;
    if (tag == 520) {
        // 记录
        AuctionOrderListVC *vc = [[AuctionOrderListVC alloc] init];
        vc.isShowTabBar = false;
        vc.gk_navTitle = @"成交记录";
        [self.navigationController pushViewController:vc animated:true];
    }else if (tag == 521) {
        // 我的地址
        AddressListVC * adressViewVC = [[AddressListVC alloc] init];
        [self.navigationController pushViewController:adressViewVC animated:YES];
    }else if (tag == 522) {
        // 我的钱包
        WalletViewController *vc = [[WalletViewController alloc] init];
        [self.navigationController pushViewController:vc animated:true];
    }else if (tag == 523) {
        // 优惠券
        CouponViewController *vc = [[CouponViewController alloc] init];
        [self.navigationController pushViewController:vc animated:true];
    }else {}
}

/**
 下边那个view

 @param sender sender
 */
- (void)headerBottomButtonsClick:(UIButton *)sender {
    if (!(self.uid.length > 0 && self.loginKey.length > 0)) {
        [self showMessage:@"请登录"];
        return;
    }
    NSInteger index = sender.tag - 520;
    if (sender.tag == 520) {
        // 代付款
        
    }else if (sender.tag == 521) {
        // 待发货

    }else if (sender.tag == 522) {
        // 已收货
        
    }else if (sender.tag == 523) {
        // 已签收
        
    }else {
        // 全部订单
        index = 0;
    }
    MyOrderViewController * myOrderVC = [[MyOrderViewController alloc] init];
    myOrderVC.selectedCondition = (int)index;
    [self.navigationController pushViewController:myOrderVC animated:true];
}
@end
